﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CtCache;
using CtCommon.Utility;
using Cxx.BLL;
using Cxx.Common;
using Cxx.Entity;

namespace Cxx.OrderManagerSys
{
    public partial class Export : System.Web.UI.Page
    {
        public string guid;

        public int mode;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                guid = WebHelper.GetQueryString("Guid");
                mode = WebHelper.GetQueryInt("Mode");
                if (Request.HttpMethod == "POST")
                {
                    if (string.IsNullOrEmpty(guid))
                    {
                        return;
                    }
                    string condition = CacheHelper.Instance.GetObject<string>(guid);
                    if (string.IsNullOrWhiteSpace(condition))
                    {
                        Response.Write("需要导出的内容已下载完成或没有需要导出的内容");
                        Response.End();
                        return;
                    }
                    List<OrderInfo> list = Order.GetList(condition);
                    if (list == null || list.Count == 0)
                    {
                        JScript.Alert(Page, "没有可导出的内容");
                        return;
                    }
                    Dictionary<string, DataTable> dataTableDic;
                    switch ((ExportMode) mode)
                    {
                        case ExportMode.ByReceiver:
                            var receivers = GetReceiverList(list);
                            SplitDataTable(list, receivers, out dataTableDic);
                            break;
                        case ExportMode.OneSheet:
                            SplitDataTable(list, out dataTableDic);
                            break;
                        default:
                            return;
                    }
                    
                    if (dataTableDic.Count != 0)
                    {
                        AsposeExcelHelper.GetInstance()
                            .ExportToWeb("澳门赌本-" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls", dataTableDic);
                        CacheHelper.Instance.RemoveObject(guid);
                    }
                }
            }
            catch (Exception exception)
            {
                CacheHelper.Instance.RemoveObject(guid);
                throw;
            }
        }

        /// <summary>
        /// 分解dataTable
        /// </summary>
        /// <param name="originalOrder"></param>
        /// <param name="receiverList"></param>
        /// <param name="dataTableDic"></param>
        /// <returns></returns>
        private static void SplitDataTable(List<OrderInfo> originalOrder, IReadOnlyList<string> receiverList, 
            out Dictionary<string, DataTable> dataTableDic)
        {
            dataTableDic = new Dictionary<string, DataTable>();
            int i = 1;
            dataTableDic.Add("目录", CreateCatalog(receiverList));
            foreach (var receiver in receiverList)
            {
                var list = originalOrder.FindAll(p => p.Receiver.Equals(receiver));
                var exportList = TransferInfos(list);
                var table = TableHelper.GetDataTable(exportList, GetTitle());
                dataTableDic.Add(i++ + "-" + receiver, table);
            }
        }

        /// <summary>
        /// 分解dataTable
        /// </summary>
        /// <param name="originalOrder"></param>
        /// <param name="dataTableDic"></param>
        /// <returns></returns>
        private static void SplitDataTable(List<OrderInfo> originalOrder, out Dictionary<string, DataTable> dataTableDic)
        {
            dataTableDic = new Dictionary<string, DataTable>();
            var exportList = TransferInfos(originalOrder);
            var table = TableHelper.GetDataTable(exportList, GetTitle());
            dataTableDic.Add("总表", table);
        }

        private static DataTable CreateCatalog(IReadOnlyList<string> receiverList)
        {
            string[] columnNames =
            {
                "Sheet序号", "收货人"
            };

            List<CatalogInfo> list = new List<CatalogInfo>();

            for (int i = 0; i < receiverList.Count; i++)
            {
                list.Add(new CatalogInfo {Id = (i + 1).ToString(), Name = receiverList[i]});
            }
            return TableHelper.GetDataTable(list, columnNames);
        }

        /// <summary>
        /// 获取收货人列表
        /// </summary>
        /// <param name="orderList"></param>
        /// <returns></returns>
        private List<string> GetReceiverList(IEnumerable<OrderInfo> orderList)
        {
            var sourceReceiverList = orderList.Select(p => p.Receiver).ToList();
            return sourceReceiverList.Distinct().ToList();
        }

        private static string[] GetTitle()
        {
            return new[] {"单号", "日期", "收货人", "名称", "数量", "单价", "倍数", "金额", "合计", "是否已结", "有无单子", "备注"};
        }

        private static List<ExportOrderInfo> TransferInfos(IEnumerable<OrderInfo> infos)
        {
            List<ExportOrderInfo> result = new List<ExportOrderInfo>();
            foreach (var info in infos)
            {
                var detailInfos = info.Detail?.JSONDeserialize<List<DetailInfo>>() ?? new List<DetailInfo>();
                ExportOrderInfo exportOrderInfo = new ExportOrderInfo
                {
                    TotalAmount = info.Amount,
                    Date = info.Time.ToString("yyyy-MM-dd HH:mm:ss"),
                    IsFinished = info.Paymented ? "已结" : "未结",
                    HasOrder = info.HasOrder?"有":"无",
                    OrderCode = info.OrderCode,
                    Receiver = info.Receiver
                };
                foreach (var detailInfo in detailInfos)
                {
                    exportOrderInfo.Name += detailInfo.Name + Environment.NewLine;
                    exportOrderInfo.Count += detailInfo.Count + Environment.NewLine;
                    exportOrderInfo.UnitPrice += detailInfo.UnitPrice + Environment.NewLine;
                    exportOrderInfo.Amount += detailInfo.Total + Environment.NewLine;
                    if (string.IsNullOrWhiteSpace(detailInfo.Times) || detailInfo.Times == "0")
                    {
                        detailInfo.Times = "1";
                    }
                    exportOrderInfo.Times += detailInfo.Times + Environment.NewLine;
                }
                exportOrderInfo.Name = exportOrderInfo.Name?.TrimEnd(Environment.NewLine.ToCharArray()) ?? string.Empty;
                exportOrderInfo.Count =
                    exportOrderInfo.Count?.TrimEnd(Environment.NewLine.ToCharArray()) ?? string.Empty;
                exportOrderInfo.UnitPrice = exportOrderInfo.UnitPrice?.TrimEnd(Environment.NewLine.ToCharArray()) ??
                                            string.Empty;
                exportOrderInfo.Amount =
                    exportOrderInfo.Amount?.TrimEnd(Environment.NewLine.ToCharArray()) ?? string.Empty;
                result.Add(exportOrderInfo);
            }
            return result;
        }
    }

    class CatalogInfo
    {
        public string Id { set; get; }

        public string Name { set; get; }
    }
}